﻿using Cc.Common;
using CC.Common;
using Common;
using SoftRegManager.BLL;
using SoftRegManager.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SoftRegManager.Forms
{
    public partial class FrmSetting : Form
    {
        private string mSettingFile = "setting.ini";
        private SettingItems mSettingItems;
       
        public  SqlSugar. DbType SqlType { get { return (SqlSugar.DbType)(cbDbTypes.SelectedIndex); } }
        public FrmSetting()
        {
            InitializeComponent();
            mSettingItems = new SettingItems
            {
                SqlType = SqlSugar.DbType.MySql,
                ConnString = "Host=localhost;UserName=root;Password=abc123;Database=SoftwareManager;"
            };
        }

        private void FrmSetting_Load(object sender, EventArgs e)
        {
            if(File.Exists(mSettingFile))
            {
                MyConfiguration cfg = new MyConfiguration(mSettingFile,true);
                cfg.ReadConfigurationsToObject(mSettingItems, mSettingFile);
                if(mSettingItems!=null)
                    LoadSettings(mSettingItems);
            }
        }

        private void LoadSettings(SettingItems settingItems)
        {
            cbDbTypes.SelectedIndex =(int) settingItems.SqlType;
            switch (settingItems.SqlType)
            {
                case SqlSugar.DbType.MySql:
                    MySqlConnectStringBuider mySb = new MySqlConnectStringBuider(settingItems.ConnString);
                    txtDbSource.Text = mySb.Source;
                    txtUser.Text = mySb.User;
                    txtPassword.Text = mySb.Password;
                    txtDbBase.Text = mySb.Database;
                    chkIntegrate.Visible = false;
                    break;
                case SqlSugar.DbType.SqlServer:
                    SqlConnectionStringBuilder msSb = new SqlConnectionStringBuilder(settingItems.ConnString);
                    txtDbSource.Text = msSb.DataSource;
                    txtUser.Text = msSb.UserID;
                    txtPassword.Text = msSb.Password;
                    txtDbBase.Text = msSb.InitialCatalog;
                    chkIntegrate.Visible = true;
                    chkIntegrate.Checked = msSb.IntegratedSecurity;
                    break;
                case SqlSugar.DbType.Sqlite:
                    chkIntegrate.Visible = false;
                    SqLiteConnectStringBuider slSb = new SqLiteConnectStringBuider(mSettingItems.ConnString);
                    txtDbSource.Text = slSb.DbFile;
                    txtPassword.Text = slSb.Password;

                    break;
                case SqlSugar.DbType.Oracle:
                    chkIntegrate.Visible = false;
                    break;
                case SqlSugar.DbType.PostgreSQL:
                    chkIntegrate.Visible = false;
                    break;
                default:
                    chkIntegrate.Visible = false;
                    break;
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            
            if(TryGenerateSettings(out mSettingItems))
            {
                MyConfiguration cfg = new MyConfiguration(true);
                cfg.WriteConfigurationsFromObject(mSettingItems, mSettingFile);
                DialogResult = DialogResult.OK;
                Close();
            }
            else
            {
                MessageBox.Show("尚不支持你选择的数据库类型","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }
        private bool TryGenerateSettings(out SettingItems settingItems)
        {
            bool ok = true;
            settingItems = new SettingItems
            {
                SqlType = (SqlSugar.DbType)cbDbTypes.SelectedIndex
            };
            switch (mSettingItems.SqlType)
            {
                case SqlSugar.DbType.MySql:
                    MySqlConnectStringBuider mySb = new MySqlConnectStringBuider
                    {
                        Source = txtDbSource.Text,
                        User = txtUser.Text,
                        Password = txtPassword.Text,
                        Database = txtDbBase.Text
                    };

                    settingItems.ConnString = mySb.ConnectString;
                    break;
                case SqlSugar.DbType.SqlServer:
                    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder
                    {
                        DataSource = txtDbSource.Text,
                        IntegratedSecurity = chkIntegrate.Checked,
                        UserID = txtUser.Text,
                        Password = txtPassword.Text,
                        InitialCatalog = txtDbBase.Text
                    };
                    settingItems.ConnString = builder.ConnectionString;
                    break;
                case SqlSugar.DbType.Sqlite:
                    SqLiteConnectStringBuider slSb = new SqLiteConnectStringBuider
                    {
                        DbFile = txtDbSource.Text,
                        Password = txtPassword.Text
                    };
                    settingItems.ConnString = slSb.ConnectString;
                    break;
                case SqlSugar.DbType.Oracle:
                    ok = false;
                    break;
                case SqlSugar.DbType.PostgreSQL:
                    ok = false;
                    break;
                default:
                    ok = false;
                    break;
            }
            return ok;
        }

        GreatBLL mbll;
        private void btnTest_Click(object sender, EventArgs e)
        {
            if(TryGenerateSettings(out mSettingItems))
            {
                mbll = new GreatBLL(mSettingItems.ConnString, mSettingItems.SqlType);
                cbTables.Enabled = false;
                try
                {
                    Cursor = Cursors.WaitCursor;
                    GetTables();
                    if (mbll.DbReady)
                    {
                        MessageBox.Show("连接成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("测试，数据库未准备好", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show("错误信息为：\r\n" + ex.Message, "测试时发生异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    Cursor = Cursors.Default;
                }
            }
            
        }

        private void btnInitial_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("初始化数据库可能会丢失数据库已有内容，确认需要继续码？","警告",MessageBoxButtons.YesNo,MessageBoxIcon.Warning)== DialogResult.Yes)
            {
                cbTables.Enabled = false;
                if (TryGenerateSettings(out mSettingItems))
                {
                    try
                    {
                        Cursor = Cursors.WaitCursor;
                        mbll = new GreatBLL(mSettingItems.ConnString, mSettingItems.SqlType);
                        if (chkClearDB.Checked)
                            mbll.DropTables();
                        mbll.CreateTables();
                       
                        if(!mbll.DbReady)
                        {//实测发现第一次总是不成功，但重复一次就好了。
                            mbll.CreateTables();
                           
                        }
                        GetTables();
                        if (mbll.DbReady)
                        {
                            MessageBox.Show("初始化成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            MessageBox.Show("初始化失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("错误信息为：\r\n" + ex.Message, "初始化失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        Cursor = Cursors.Default;
                    }
                   
                }
                
            }
            
            
        }

        private void GetTables()
        {
            
            var tables = mbll.GetTables();
            cbTables.Items.Clear();
            foreach (var table in tables)
            {
                cbTables.Items.Add(table.Name);
            }
            cbTables.Enabled = true;
        }

        private void cbTables_SelectedIndexChanged(object sender, EventArgs e)
        {
            var columns = mbll.GetDbColumnInfos(cbTables.Text);
            listBox1.Items.Clear();
            listBox1.Items.Add("ColumnName  DataType Length  IsPrimaryKey");
            listBox1.Items.Add("----------------------------------");
            foreach (var col in columns)
            {
                listBox1.Items.Add(col.DbColumnName+" | "+col.DataType+" | "+col.Length+" | "+col.IsPrimarykey);
            }
        }

        private void cbDbTypes_SelectedIndexChanged(object sender, EventArgs e)
        {

            var dbType = (SqlSugar.DbType)cbDbTypes.SelectedIndex;
           
            switch (dbType)
            {
                case SqlSugar.DbType.MySql:
                    break;
                case SqlSugar.DbType.SqlServer:
                    break;
                case SqlSugar.DbType.Sqlite:
                    btnBrowse.Visible = true;
                    lbDBase.Visible = false;
                    txtDbBase.Visible = false;
                    lbUser.Visible = false;
                    txtUser.Visible = false;
                    txtPassword.Text = "";
                    break;
                case SqlSugar.DbType.Oracle:
                    break;
                case SqlSugar.DbType.PostgreSQL:
                    break;
                default:
                    break;
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog
            {
                Title = "选择SqLite数据库文件",
                RestoreDirectory = true,
                InitialDirectory=Environment.CurrentDirectory,
                Filter = "All SqLite Databases(*.db;*.sdb;*.sqlite;*.db3;*.s3db;*.sqlite3;*.sl3;*.db2;*.s2db;*.sqlite2;*.sl2)|*.db;*.sdb;*.sqlite;*.db3;*.s3db;*.sqlite3;*.sl3;*.db2;*.s2db;*.sqlite2;*.sl2" +
                "|SqLite3 Databases(*.db3;*.s3db;*.sqlite3;*.sl3)|*.db3;*.s3db;*.sqlite3;*.sl3" +
                "|SqLite2 Databases(*.db2;*.s2db;*.sqlite2;*.sl2)|*.db2;*.s2db;*.sqlite2;*.sl2" +
                "|All Files(*.*)|*.*",
                FilterIndex=0
            };
            if(fd.ShowDialog()== DialogResult.OK)
            {
                txtDbSource.Text = fd.FileName;
            }
        }
    }
}
